from werkzeug.utils import redirect

from odoo import http
from odoo.addons.basic_configuration.config.env_config import switch_env
from odoo.addons.basic_configuration.decorate.controller_exception_handler import exception_handler, PayException
from odoo.addons.rp_finance_management.functions.rp_finance_related_func import RpFinanceRelatedFunc
from odoo.http import request


class OrderPayController(http.Controller):

    @http.route('/qr_code/pay', type='http', auth='public', method=['GET'])
    @exception_handler
    def qr_code_pay(self, order_id, balance_price, stripe_price, total_price):
        """
        二维码支付逻辑（扫描二维码后触发的逻辑）
        """
        # 查找数据
        rp_ship_order_id = request.env['rp.ship.order'].sudo().search([('id', '=', order_id)])
        if rp_ship_order_id.state in ['done', 'invoiced']:
            # 装饰器触发跳转页面,装饰器进行跳转
            raise PayException('订单已支付')
        rp_ship_order_payment_id = request.env['rp.payment'].sudo().search([('advance_document_id.field_record_id', '=', int(order_id)),
                                                                            ('advance_document_id.field_name_id', '=', request.env['ir.model'].sudo().search([('model', '=', 'rp.ship.order')]).id)])
        balance_tag, stripe_tag = False, False
        if float(balance_price) != 0.0:
            balance_tag = True
        if float(stripe_price) != 0.0:
            stripe_tag = True
        # 更新支付单
        order_payment_id = RpFinanceRelatedFunc(request.env).update_payment(rp_ship_order_id=rp_ship_order_id,
                                                                            rp_ship_order_payment_id=rp_ship_order_payment_id,
                                                                            balance_tag=balance_tag,
                                                                            stripe_tag=stripe_tag,
                                                                            stripe_price=float(stripe_price),
                                                                            balance_price=float(balance_price),
                                                                            order_total_price=float(total_price)
                                                                            )
        rp_ship_order_id.write({'click_pay_flag': True})  # 表示已经触发过支付
        # stripe支付
        if stripe_tag:
            #  进行Stripe支付
            pay_url = RpFinanceRelatedFunc(request.env).stripe_pay(pay_price=float(stripe_price), request=request, way='qr_code', payment_code=order_payment_id.code)
            # 跳转到指定页面
            return redirect(pay_url)

        # 适用于只有余额支付时的确认支付
        rp_ship_order_id.with_context({'payment_code': order_payment_id.code}).action_for_pay()
        target_ur = '{}?successfully_order_id={}'.format(switch_env['h5_url']['url'], rp_ship_order_id)
        return redirect(target_ur)
